package com.klun.concDesign.chapterFour.V4_4_8;

import java.util.concurrent.atomic.AtomicReferenceArray;

/**
 * 挑战无锁的算法：无锁的 Vector 实现
 * @param <E>
 */
public class Descriptor<E> {
    public int size;
    volatile WriteDescriptor<E> writeop;

    public Descriptor(int size, WriteDescriptor<E> writeop) {
        this.size = size;
        this.writeop = writeop;
    }

    public void completeWrite(){
        WriteDescriptor<E> tmpOp = writeop;
        if(tmpOp != null){
            tmpOp.doIt();
            writeop = null;
        }
    }
    static class WriteDescriptor<E>{

        public E oldV; // 旧值
        public E newV; // 新值
        public AtomicReferenceArray<E> addr;
        // ?????  偏移量 表示要修改的原子数组
        public int addr_ind;

        public WriteDescriptor(AtomicReferenceArray<E> addr, int addr_ind, E oldV, E newV) {
            this.oldV = oldV;
            this.newV = newV;
            this.addr = addr;
            this.addr_ind = addr_ind;
        }

        public void doIt(){
            addr.compareAndSet(addr_ind,oldV,newV);
        }
    }
}
